package com.example.demo.controller;

import com.example.demo.Service.IShoppingService;
import com.example.demo.core.Result;
import com.example.demo.entity.ShoppingCart;
import com.example.demo.entity.params.ShoppingCartAddParam;
import com.example.demo.entity.vo.ShoppingCartVo;
import com.example.demo.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/shopping")
@CrossOrigin(origins = "*")
public class ShoppingController {

    @Autowired
    private IShoppingService shoppingService;

    @PostMapping("/cartAdd")
    public Map<String,Object> add(HttpServletRequest request, @RequestBody ShoppingCartAddParam shoppingCartAddParam){

        int rs = shoppingService.shoppingCartAdd(JWTUtil.getUserId(request.getHeader("Authorization")),shoppingCartAddParam.getProductId());

        Map<String,Object> map = new HashMap<>();
        if (rs>0){

            map.put("code",200);
            map.put("msg","操作成功");

        }
        else {
            map.put("code",500);
            map.put("msg","操作失败");
        }

        return map;
    }

    @GetMapping("/cartSelect")
    public Map<String,Object> select(HttpServletRequest request){

        List<ShoppingCartVo> shoppingCartVos = shoppingService.list(JWTUtil.getUserId(request.getHeader("Authorization")));

        Map<String,Object> map = new HashMap<>();

        map.put("code",200);
        map.put("msg","查询成功！");
        map.put("data",shoppingCartVos);

        return map;

    }

    @PostMapping("/reviseNum")
    public Map<String,Object> revise(Long shoppingCartId,Long num){
        int rs = shoppingService.NumAdd(shoppingCartId,num);

        Map<String,Object> map = new HashMap<>();

        if (rs>0){

            map.put("code",200);
            map.put("msg","操作成功");

        }
        else {
            map.put("code",500);
            map.put("msg","操作失败");
        }
        return map;
    }

    @DeleteMapping("/delete/{shoppingCartId}")
    public Map<String,Object> delete(@PathVariable Long shoppingCartId){
        int rs = shoppingService.delete(shoppingCartId);

        Map<String,Object> map = new HashMap<>();

        if (rs>0){

            map.put("code",200);
            map.put("msg","操作成功");

        }
        else {
            map.put("code",500);
            map.put("msg","操作失败");
        }
        return map;
    }

    @GetMapping("/count")
    public Result count(HttpServletRequest request){
        return Result.success(shoppingService.count(request));
    }

}
